package controllers;

import java.util.List;

import models.User;
import models.ZipcodeGeo;
import play.i18n.Messages;
import play.libs.OpenID;
import play.libs.OpenID.UserInfo;
import play.mvc.Controller;
import play.mvc.With;
import util.GoogleGeocode;
import util.GoogleGeocode.GeocodeException;

import com.javadocmd.simplelatlng.LatLng;

@With(Common.class)
public class Application extends Controller {

	public static void index() {
		Find.view();
	}

	public static void about() {
		render();
	}

	public static void login() {
		render();
	}

	public static void logout() {
		session.clear();
		index();
	}

	public static void listZipcodes() {
		List<ZipcodeGeo> zipcodes = ZipcodeGeo.all().fetch();
		render(zipcodes);
	}

	public static void rawGeocode(String address) {
		String geocodeResults = null;
		LatLng latLng = null;
		try {
			GoogleGeocode gg = new GoogleGeocode("US", "postal_code");
			geocodeResults = gg.geocodeRaw(address);
			latLng = gg.geocode(address);
		} catch (GeocodeException e) {
			e.printStackTrace();
			flash.error("Geocode exception encountered.");
		}
		render(geocodeResults, latLng);
	}

	public static void authenticate(String user) {
		if (OpenID.isAuthenticationResponse()) {
			UserInfo verifiedUser = OpenID.getVerifiedID();
			if (verifiedUser == null) {
				flash.error(Messages.get("openid.loginFailed"));
				login();
			}

			session.put("openid", verifiedUser.id);
			User u = User.getUser(session);
			if (u == null)
				Profile.edit();
			else
				index();
		} else {
			if (!OpenID.id(user).verify()) {
				flash.error(Messages.get("openid.cannotVerify"));
				login();
			}
		}
	}
}